﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Inspired.Euler
{
    public static class Problem032
    {
        /// <summary>
        /// Find the sum of all numbers that can be written as pandigital products.
        /// </summary>
        [EulerProblem(32, Title = "Find the sum of all numbers that can be written as pandigital products.")]
        public static long Solve()
        {
            //Console.WriteLine(IsPandigitalIdentity(39, 186, 7254));
            //Console.WriteLine(IsPandigitalIdentity(1, 0, 123));

            Dictionary<long, object> products = new Dictionary<long,object>();
            for (int multiplicand = 1; multiplicand < 98765; multiplicand++)
            {
                int m1 = 1 + (int)Math.Log10(multiplicand);
                for (int multiplier = 1; multiplier < 98765; multiplier++)
                {
                    int product = multiplicand * multiplier;

                    if (products.ContainsKey(product))
                        continue;   // HINT

                    int m2 = 1 + (int)Math.Log10(multiplier);
                    int p = 1 + (int)Math.Log10(product);

                    if ((m1 + m2 + p) < 9)
                        continue;   // ainda nao chegou

                    if ((m1 + m2 + p) > 9)
                        break;  // passou de 9 caracteres

                    //Console.Title = string.Format("{0}, {1}, {2}", m1, m2, p);
                    if (IsPandigitalIdentity(multiplicand, multiplier, product))
                    {
                        products.Add(product, null);
                    }
                }
            }
            return products.Keys.Sum();
        }

        static bool IsPandigitalIdentity(long multiplicand, long multiplier, long product)
        {
            return
                multiplicand.AsEnumerable().Concat(
                multiplier.AsEnumerable().Concat(
                product.AsEnumerable()))
                    .IsPandigital();
        }
    }
}
